var toast = require('../../../components/toast/toast.js')
var app = getApp();

Page({
  data: {
    //主键
    carId: 0,
    // 被选中的违章violationid，请求支付的参数；补充资料入口才有数据
    idlist: [],
    // 需要补充的资料列表
    NeedDataList: {},
    // 已有资料列表
    ExistDataList: {},

    //备份已有资料的对象
    NeedData: {},
    // 初始化图片
    PhoneList: [],
    Tap: '', // 记录是哪个按钮被点击
    //  PhoneDrivingImg: '',
    // 顶部提示显示
    hits: '',
    // 列表先隐藏
    formHide: 'hide'
  },
  onLoad: function (options) {
    let list = [];
    let backendid = options.unidList ? options.unidList : [];
    let violaid = options.violationidList ? options.violationidList : [];
    let listLEN = violaid.length ? true : false;

    list.push(backendid, violaid, listLEN); // 第一个为backendid；第二个为violaid，第三为true是补充资料入口，false是修改资料入口
    this.setData({
      carId: options.carId,
	    backendIdList: backendid, //试算接口需要的参数
      idlist: list,
      NeedDataList: {},
      ExistDataList: {},
      PhoneList: [],
      Tap: '',
      hits: '',
      formHide: 'hide'
    });
  },
  onReady: function () {
  },
	onLaunch:function () {

	},
  onShow: function () {
	  this.initialization();
  },
  onHide: function () {
  },
  onUnload: function () {
    this.setData({
      carId: 0,
      idlist: [],
      NeedDataList: {},
      ExistDataList: {},
      PhoneList: [],
      Tap: '',
      hits: '',
      formHide: 'hide'
    });
    // 页面关闭
  },
  /**
   * 页面初始化
   */
  initialization: function () {
    console.log('初始化请求')
    let listLEN = this.data.idlist[2]; // true是补充入口，false是修改入口
    this.getExistDataList();  // 请求已经填写的资料
    //  从修改入口，长度为0，从补充入口进来才有idlist记录
    if (listLEN) {
      wx.setNavigationBarTitle({ title: "补充资料" });
      this.getNeedDataList();  // 请求需要加载的资料
    } else {
      wx.setNavigationBarTitle({ title: "修改资料" });
    }

  },
  /**加载已经填写过资料 */
  getExistDataList: function (e) {

    let listLEN = this.data.idlist[2]; // true是补充入口，false是修改入口
    let _this = this;
    var param = {
      api: 'Service.UcCar.CarService.SelectCarRequirements',
	    url: '/wx/carViola/selectCarRequirements.ajax',
	    para: {
        'carId': this.data.carId 
      }
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行
        wx.showToast({
          title: '请稍候',
          icon: 'loading',
          duration: 10000,
          mask: true
        });
      },
      success: data => {
        var sign={};
        if (data.successFlag) {
          for(var key in data.data){
            if(data.data[key]&&data.data[key]!='null'){
              sign[key] = data.data[key]
            }
          }
          _this.setData({
            ExistDataList: sign, //data.data
            NeedData: sign
          });
          // 从修改入口，长度为0,false；输出页面
          if (!listLEN) _this.outputList();

        } else {
          wx.hideToast();
          toast.show(this, data.errormsg)
        }

      },

      complete: data => {
        // wx.hideToast();
      }
    });
  },
  /**请求需要加载的资料 */
  getNeedDataList: function (e) {
    let _this = this;
    var param = {
	    url: '/wx/carViola/getPeccNeedRequirement.ajax',
	    para: {
        'localUniqueId': this.data.idlist[0], 
        'carId': this.data.carId 
      }
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
       
      },
      success: data => {
        if (data.successFlag) {
          this.setData({
            NeedDataList: data.data
          });

          let a = this.data.ExistDataList; // 已有资料列表
          // 要有数据才输出页面
          let timer = setInterval(function () {
            if (Object.keys(a).length > 0) {
              clearInterval(timer);
              _this.outputList(); // 页面输出
            }
          }, 250);

        } else {
          wx.hideToast();
          toast.show(this, data.errormsg)
        }
      },
      complete: data => {
      }
    });

  },
  /**
   * 通过上面的数据，输出页面列表
   */
  outputList: function () {
    //页面加载
    let needList = this.data.NeedDataList;
    let existList = this.data.ExistDataList;
    let listLEN = this.data.idlist[2];
    let detailList = app.deepClone(app.globalData.furtherProperties); // 默认数app.globalData.furtherProperties;  // 默认数据
    // console.log('detailList =',detailList);
    let list = [];

    if (listLEN) {
      // 1、从补充资料入口
      for (var key in needList) {
        if (needList[key]) { // 接口数据不为0，的显示输入框
          let info = detailList[key];
          info.maxlength = needList[key] == 99 ? info.maxlength : JSON.parse(needList[key]);
          // 检验输入值 ；发动机和车身架号 有输入，但位数不对
          let key_length = info.value.length ? info.value.length : 0;

          if ((key == "CarDriveLen" || key == "CarCodeLen") && info.maxlength < 99 ) {
            info.placeholder = '请输入' + info.display + '后' + info.maxlength + '位';
          }
          else if ((key == "CarDriveLen" || key == "CarCodeLen") && info.maxlength == 99)
            info.placeholder = '请输入完整的' + info.display;
            list.push(info);
        }
      }
    } else {
      for (var key in existList) {
        if (detailList.hasOwnProperty(key)) {
          detailList[key].value = existList[key];
          list.push(detailList[key]);
        }
      }
    }
    // 把值放到默认数据里面
    this.setData({
      NeedDataList: list,
      ExistDataList: {},
      formHide: ''
      //  PhoneIndex: PhoneIndex
    }); // 数据覆盖

    setTimeout(function () {
      wx.hideToast()
    }, 500);

  },
  /*
  *   上传图片事件
  *
	uploadTap:function (e) {
		var type = e.currentTarget.dataset.type;
		var value = e.currentTarget.dataset.value;
		app.navigateTo({
			url: '../furtherInfor/upload/upload?type='+type+'&uploadImgSrc='+value
		});
	},
  /**
   * 输入框 大写
   */
  bindKeyInput: function (e) { 
    let needData = this.data.NeedDataList;
    let type = e.currentTarget.dataset.type;
    let value = e.detail.value;
    for(var i = 0;i<needData.length;i++){
      if(needData[i].key == type){
          needData[i].value = value
      }
    }

    return value.replace(/[a-z]/g, function (ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); });
  },

  /**
  * 检验输入和要求的长度是否一致
  */
  verifyValueFromEdit: function (item) {
    let h = '';

    if (item.key == 'CarOwnerPhoneLen' || item.key == 'FilePhoneLen') {
      if (item.maxlength != item.value.length) {
        item.placeholder = '请输入' + item.maxlength + '位' + item.display;

        return item.placeholder; // return 有值说明有检验有问题
      }

    }
    return h;
    // 
  },
  verifyValue: function (item) {
    let h = '';

    if ((item.key == 'CarDriveLen' || item.key == 'CarCodeLen') && item.maxlength < 99 && item.maxlength != item.value.length) {
      item.placeholder = '请输入' + item.display + '后' + item.maxlength + '位';
      return item.placeholder; // return 有值说明有检验有问题
    }

    // 如果是数字或者身份证types输入，//直接检验正则
    if (item.pattern) { // 检验正则
       let detailList =app.globalData.furtherProperties[item.key]; // 默认数app.globalData.furtherProperties;  // 默认数据
      if (!(detailList.pattern.test(item.value.trim()))) {
        item.placeholder = '请输入正确的' + item.display;
        return item.placeholder; // return 有值说明有检验有问题
      }
    }
    return h;
    // if (item.maxlength == 99) {
    //   item.placeholder = '请输入完整的' + item.display ;
    //   return item.placeholder; // return 有值说明有检验有问题
    // }
  },
  /** 
   * 上传图片
   */
  // 照片按钮
  chooseImageTap: function (e) {
    this.setData({
      Tap: e.target.id
    });
    let _this = this;
    this.imgShow(_this);

  },
  //用来显示一个选择图片和拍照的弹窗，用到了微信的一个页面交互的api showActionSheet　
  imgShow: function (e) {
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            e.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            e.chooseWxImage('camera')
          }
        }
      }
    })
  },

  //主要是用来选择图片以及接收图片路径回调的监听
  chooseWxImage: function (type) {
    let _this = this;
    let PhoneList = this.data.NeedDataList;
    let Tap = this.data.Tap;
    console.log(PhoneList)
    wx.chooseImage({
      count: 1,                             // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
         setTimeout(()=>{
          var img =  res.tempFilePaths[0];
          _this.exChangeImg(img,function (imgSrc) {
            PhoneList.map(item => {
              if (item.key == Tap) {
                // item.value = res.tempFilePaths[0];
                 item.value = imgSrc
              }
           });

            setTimeout(function () {
              _this.setData({
                //PhoneList: PhoneList.push(res.tempFilePaths[0])
                NeedDataList: PhoneList,
                fileData: PhoneList
              })
            },1000)
  
          })

         },250)        
      },
      fail: function () {
        toast.show(this, '图片上传失败，请重新上传', 2000);/// toast
      }
    })
  },

  /*
  *   请求接口返回https图片途径
  * */
	exChangeImg: function (uploadImgSrc,callBack) {
		var pageObj = this;

		if(uploadImgSrc==''){
			app.errorToast("请选择图片！");
			return false;
		}
		var opt = {
			filePath:uploadImgSrc,
			params:{uploadType:'03',owner:app.globalData.userInfo.openId||'123456'},
			success: function (res) {    //上传成功将数据保存到缓存中
				var dataObj=JSON.parse(res.data);
				if(dataObj.code==1000){
          typeof callBack == 'function'&& callBack(dataObj.body.imageUrl)
				}
			},
			fail:function (res) {
			}
		};

		app.uploadFile(opt);

  },

  /**
   * 保存按钮
   */
  createOrUpdate: function (e) {
    let fileData = this.data.fileData;
    const inputList = e.detail.value; // 实际输入的数据
    let List = this.data.NeedDataList;
    let listLEN = this.data.idlist[2];// true是补充入口，false是修改入口
    
    let placeholder = '';
    let _this = this;
    let NeedData = this.data.NeedData;


    if(!listLEN){ //修改入口

    }

    for(var i=0;i<List.length;i++){
      if(List[i].types == 'img'){
        if(List[i].value == ''){
          this.setData({
            hits: '请输入需要补充的资料'
          });
          return;
        }
      }
    }

    if(JSON.stringify(inputList)!='{}') {
	    // 验证是否为空
	    for (var key in inputList) {
		    if (!inputList[key]) {
			    // 如果输入值为空，则提示，并退出循环
			    this.setData({
				    hits: '请输入需要补充的资料'
			    });
          return;
		    }
	    }
	    // 不为空，则开始：赋值，然后计算
	    for (var i = 0; i < List.length; i++) {
		    List[i].value = inputList[List[i].key];
		    // 判断入口，加载不同的验证
		    if (listLEN) placeholder = this.verifyValue(List[i]);
		    else placeholder = this.verifyValueFromEdit(List[i]);
		    if (placeholder) {
			    this.setData({ hits: placeholder });
			    return;
		    }
      }
      
     // if(fileData&&fileData.length){
        //修改图片
        for(var key in NeedData){
          if(NeedData[key].substr(0,4) == 'http'){
            if(fileData!=undefined&&fileData.length>0){
              for(var n = 0;n<fileData.length;n++){
                if(fileData[n].types == 'img'){
                  if(fileData[n].key == key){
                    List[n].value = fileData[n].value
                  }
                }
              }
            }
///
          }
        }
      //}
      

      //if(List&&List.lengt){
        for(var y = 0;y<List.length;y++){
          if(fileData!=undefined&&fileData.length>0){
            for(var n = 0;n<fileData.length;n++){
              if(List[y].value == ''||List[y].value == undefined){
                List[y].value = fileData[y].value
              }
            }
          }
         }

        for(var y = 0;y<List.length;y++){
          if(fileData!=undefined&&fileData.length>0){
            for(var n = 0;n<fileData.length;n++){
              if(List[y].value == ''||List[y].value == undefined){
                List[y].value = fileData[y].value
              }
            }
          }
        }

      }      
   // }

  
    // 这里表示数据通过验证，可以请求
    wx.showToast({
      title: '请稍候',
      icon: 'loading',
      duration: 10000,
      mask: true
    });
    this.setData({
      NeedDataList: List,
      hits: ''
    });

    setTimeout(function () {
      _this.submitDataList(List);  // 请求
      placeholder = 'postStart';
    }, 200);
    let timer = setTimeout(function () {
      if (placeholder) {
        clearTimeout(timer);
      } else {
        _this.submitDataList(List);  // 请求
      }
      placeholder = 'postStart';
    }, 10000);
    
    this.setData({
      NeedDataList: List,
      hits: ''
    });

  },

  /**提交的资料 */
  submitDataList: function (NeedDataList) {
    let list = {};
    //let NeedDataList = this.data.NeedDataList;
    let listLEN = this.data.idlist[2];
    let postJson = {};
    let _this = this;

    // 遍历出请求的参数：对象数组
    // postJson['carId'] = this.data.carId;
    app.getUserInfo(function (userinfo) {
      // postJson['userId'] = userinfo.userId
    });
    for (var j = 0; j < NeedDataList.length; j++) {
      postJson[NeedDataList[j].key] = NeedDataList[j].value;
    }
    list['requirements'] = postJson;

    //  请求
    var param = {
	    url: '/wx/carViola/addCarRequirement.ajax',
	    para: {
        'propertyJson': JSON.stringify(postJson),
        'carId': this.data.carId  
      }
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //  发送请求之前执行
      },
      success: data => {
        if (data.successFlag) {
          // 页面跳转 
          if (listLEN) {
            // 1、从补充资料入口
            wx.redirectTo({
              url: '../determineOrder/determineOrder?unidList=' + _this.data.idlist[1] + '&carId=' + _this.data.carId + '&backendIdList=' + _this.data.backendIdList
            })
          }
          else {
            // 2、从修改资料入口
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500,
              mask: true
            });
            setTimeout(function () {
              wx.navigateBack({
                delta: 2
              })
            }, 1000);
          }

        } else {
          // 请求失败
          wx.hideToast();
          toast.show(_this, data.errormsg, 3000)
        }
      },
      fail: data => {
        toast.show(_this, data.errormsg, 3000)
      },
      complete: data => {
        setTimeout(function () {
          wx.hideToast();
        }, 500);
      }
    });

  },
})